package com.onlyxiahui.wofa.server.socket.netty.websocket.impl;

import com.onlyxiahui.framework.action.dispatcher.general.GeneralMessageHandler;
import com.onlyxiahui.wofa.server.net.core.session.SocketSessionHandler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.ssl.SslContext;

/**
 */
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {

	private String websocketPath;
	private GeneralMessageHandler messageHandler;
	private SocketSessionHandler sessionHandler;
	private final SslContext sslContext;

	public WebSocketServerInitializer(
			String websocketPath,
			GeneralMessageHandler messageHandler,
			SocketSessionHandler sessionHandler,
			SslContext sslContext) {
		this.websocketPath = websocketPath;
		this.messageHandler = messageHandler;
		this.sessionHandler = sessionHandler;
		this.sslContext = sslContext;
	}

	@Override
	public void initChannel(SocketChannel sh) throws Exception {
		ChannelPipeline pipeline = sh.pipeline();
		if (sslContext != null) {
			pipeline.addLast(sslContext.newHandler(sh.alloc()));
		}
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast(new HttpObjectAggregator(65536));
		pipeline.addLast(new WebSocketServerCompressionHandler());
		pipeline.addLast(new WebSocketServerProtocolHandler(websocketPath, null, true));
		pipeline.addLast(new WebSocketFrameHandler(messageHandler, sessionHandler));
	}
}
